package com.itheima.filter;


import com.alibaba.fastjson.JSONObject;
import com.itheima.pojo.Result;
import com.itheima.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Author: Zheng
 * Date:   2024/1/25  20:43
 * Package：com.itheima.filter
 * Description：拦截器
 * Version：1.0
 */
@Slf4j
//@WebFilter(urlPatterns = "/*")
public class LoginCheckFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;

        //获取请求的url
        String url = req.getRequestURI().toString();
        log.info("请求的url为：{}", url);
        //判断请求的url是否包含login，如果包含说明在执行登录操作，放行请求
        if (url.contains("login")) {
            log.info("登录操作，放行~~~~~。。");
            chain.doFilter(request, response);
            return;
        }
        Result error = Result.error("NOT_LOGIN");
        //获取请求头中的令牌  token
        String jwt = req.getHeader("token");
        //判断令牌是否存在，不存在返回错误结果（未登录）
        if (!StringUtils.hasLength(jwt)) {
            log.info("token为空，未登录。。。。");

            //将Result对象手动转换为json----阿里巴巴fastJSON
            String notLogin = JSONObject.toJSONString(error);
            resp.getWriter().write(notLogin);
            return;
        }

        //解析token，如果解析失败，返回错误结果
        try {
            JwtUtils.parseJWT(jwt);
        } catch (Exception e) {
            e.printStackTrace();
            log.info("解析令牌失败，返回未登录错误信息！");
            String notLogin = JSONObject.toJSONString(error);
            resp.getWriter().write(notLogin);
            return;
        }

        //放行
        log.info("令牌合法，放行。。。。。。");
        chain.doFilter(request, response);
    }

}
